#include "simpleprotosrv.h"


SimpleProtoSrv::SimpleProtoSrv(ProtocolType pt) : ProtoSrv(pt)
{
}


void SimpleProtoSrv::addString(const std::string &data)
{
    _data.push_back(data);
}


void SimpleProtoSrv::addLong(long data)
{
    QString str;
    str.setNum(data);
    _data.push_back(str.toStdString());
}

bool SimpleProtoSrv::getString(std::string& data,int idx) const
{
    if(idx < size()){
        data = _data[idx];
        return true;
    }

    return false;
}

bool SimpleProtoSrv::getLong(long& data,int idx) const
{
    bool result = false;
    std::string str;

    if(getString(str,idx)){
        QString qs(str.c_str());
        data = qs.toLong(&result);
    }

    return result;
}

bool SimpleProtoSrv::encode(ACE_OutputCDR &cdr)
{
    cdr << ACE_CDR::Short(_data.size());
    if(_data.size()){
        for(int i = 0; i < (int)_data.size(); i++){
            std::string &data = _data[i];
            cdr << ACE_CDR::UShort(data.length());
            if(data.length())
                cdr.write_char_array(data.c_str(),data.length());
        }
    }

    return cdr.good_bit();
}

ProtoSrv* SimpleProtoSrv::decode(ACE_InputCDR &cdr)
{
    SimpleProtoSrv *request = new SimpleProtoSrv(this->getProtocolType());
    if(!decode(cdr,request)){
        delete request;
        request = 0;
    }

    return request;
}


bool SimpleProtoSrv::decode(ACE_InputCDR &cdr,SimpleProtoSrv* request)
{
    if(request == 0)
        return false;

    ACE_CDR::UShort size;
    if(cdr >> size && size)
    {
        for(int i = 0; i < size; i++)
        {
            ACE_CDR::UShort len;
            if(cdr >> len)
            {
                ACE_TCHAR str[len + 1];
                cdr.read_char_array(str,len);
                str[len] = '\0';

                request->_data.push_back(str);
            }
        }
    }

    return cdr.good_bit();
}


ProtoSrv* SimpleProtoSrv::execute(ACE_SOCK_Stream &peer)
{
    ACE_OutputCDR cdr;
    if(ProtoSrvManager::getInstance()->encode(cdr,this)) {
        ssize_t sent_len = peer.send_n(cdr.begin());
        if(sent_len != (ssize_t)cdr.total_length())
            return (ProtoSrv*)E_FAIL;
    }

    return E_SUCCESS;
}

